//
//  ChangeEnvironmentController.m
//  YiShangbao
//
//  Created by simon on 17/4/6.
//  Copyright © 2017年 com.Microants. All rights reserved.
//

#import "ChangeEnvironmentController.h"
#import "ChangeEnvironmentManager.h"
#import "NSBundle+ChangeEnvironment.h"
#import "ChangeEnvTableViewCell.h"
#import "ZXChangeEnvironmentModel.h"

@interface ChangeEnvironmentController ()<UITableViewDelegate,UITableViewDataSource>


@property (nonatomic, strong) UITableView *tableView;

@property (nonatomic, assign) ApiEnv apiEnv;

@property (nonatomic, strong) NSMutableArray *hostMArray;

@end


@implementation ChangeEnvironmentController


- (BOOL)forceEnableInteractivePopGestureRecognizer {
    return YES;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"切换环境";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"保存" style:UIBarButtonItemStyleDone target:self action:@selector(saveChangeStatue:)];
    [self setUI];
    [self addObserver:self forKeyPath:NSStringFromSelector(@selector(apiEnv)) options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    
    [self initData];
}

- (void)dealloc
{
    [self removeObserver:self forKeyPath:NSStringFromSelector(@selector(apiEnv))];
}


-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (UIStatusBarStyle)preferredStatusBarStyle
{
    if (self.statusBarStyle != UIStatusBarStyleLightContent) {
        if (@available(iOS 13.0, *)) {
            return UIStatusBarStyleDarkContent;
        } else {
            return UIStatusBarStyleDefault;
        }
    }
    return UIStatusBarStyleLightContent;
}

///比-viewDidLoad()迟
- (void)setStatusBarStyle:(UIStatusBarStyle)statusBarStyle{
    
    if (_statusBarStyle != statusBarStyle) {
        _statusBarStyle = statusBarStyle;
    }
}

- (NSMutableArray *)hostMArray{
    if (!_hostMArray) {
        _hostMArray = [NSMutableArray array];
    }
    return _hostMArray;
}

- (void)initData{
    self.apiEnv = ChangeEnvironmentManager.apiEnv;
    NSArray *array = [ChangeEnvironmentManager allApiEnvConfigu];
    [self.hostMArray addObjectsFromArray:array];
    
    [self.hostMArray enumerateObjectsUsingBlock:^(ZXChangeEnvironmentModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *host = obj.hostUrl;
        if (self.apiEnv == ApiEnvProd) {
            if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].prodHost]) {
                obj.isSelected = YES;
            }else{
                obj.isSelected = NO;
            }
        }
        else if (self.apiEnv == ApiEnvPre) {
            if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].preHost]) {
                obj.isSelected = YES;
            }else{
                obj.isSelected = NO;
            }
        }
        else if (self.apiEnv == ApiEnvTest) {
            if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].testHost]) {
                obj.isSelected = YES;
            }else{
                obj.isSelected = NO;
            }
        }
        else if (self.apiEnv == ApiEnvDaily) {
            if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].dailyHost]) {
                obj.isSelected = YES;
            }else{
                obj.isSelected = NO;
            }
        }
        else if (self.apiEnv == ApiEnvDev) {
            if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].devHost]) {
                obj.isSelected = YES;
            }else{
                obj.isSelected = NO;
            }
        }
        else if (self.apiEnv == ApiEnvLocal) {
            if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].localHost]) {
                obj.isSelected = YES;
            }else{
                obj.isSelected = NO;
            }
        }
    }];
    [self.tableView reloadData];
}

- (void)setUI{
 
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view.mas_left);
        make.centerX.mas_equalTo(self.view.mas_centerX);
        make.top.mas_equalTo(self.view.mas_top);
        make.bottom.mas_equalTo(self.view.mas_bottom);
    }];
    
}

#pragma mark -

- (UITableView *)tableView
{
    if (!_tableView) {

        UITableView *view = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        view.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        view.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        view.backgroundColor = [UIColor whiteColor];
        view.delegate = self;
        view.dataSource = self;
        [view registerClass:[ChangeEnvTableViewCell class] forCellReuseIdentifier:NSStringFromClass([ChangeEnvTableViewCell class])];
        _tableView = view;
    }
    return _tableView;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.hostMArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ChangeEnvTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([ChangeEnvTableViewCell class]) forIndexPath:indexPath];
    ZXChangeEnvironmentModel *model = [self.hostMArray objectAtIndex:indexPath.row];
    [cell setData:model];
    if (model.isSelected) {
        [tableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
    }
    return cell;
}



- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *oneCell = [tableView cellForRowAtIndexPath:indexPath];
    oneCell.accessoryType = UITableViewCellAccessoryNone;

}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *oneCell = [tableView cellForRowAtIndexPath:indexPath];
    if (oneCell.accessoryType == UITableViewCellAccessoryNone)
    {
        oneCell.accessoryType = UITableViewCellAccessoryCheckmark;
        
        ZXChangeEnvironmentModel *model = [self.hostMArray objectAtIndex:indexPath.row];
        [self.hostMArray enumerateObjectsUsingBlock:^(ZXChangeEnvironmentModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([model.envType isEqualToString:obj.envType]) {
                obj.isSelected = YES;
                self.apiEnv = [ChangeEnvironmentManager switchEnvStringToApiEnv:obj.envType];
            }else{
                obj.isSelected = NO;
            }
        }];
//        
//        NSDictionary *hostDic = [[ChangeEnvironmentManager allApiEnvConfigu]objectAtIndex:indexPath.row];
//        NSString *host = [hostDic objectForKey:@"host"];
//        if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].onlineHost]) {
//            self.apiEnv = ApiEnvProd;
//        }else if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].preHost]){
//            self.apiEnv = ApiEnvPre;
//        }else if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].dailyHost]){
//            self.apiEnv = ApiEnvDaily;
//        }else if ([host isEqualToString:[ChangeEnvironmentManager sharedInstance].devHost]){
//            self.apiEnv = ApiEnvDev;
//        }
//        else{
//        }
    }
}

#pragma mark -

//+ (UIViewController *)controller{
//
//    NSBundle *bundle = [NSBundle changeEnvStoryboardBundle];
//    UIStoryboard *sb=[UIStoryboard  storyboardWithName:@"ChangeDomain" bundle:bundle];
//    UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"ChangeEnvironmentController"];
//    return vc;
//}

- (void)saveChangeStatue:(UIBarButtonItem *)sender{
    [ChangeEnvironmentManager changeEnvironmentActionWithApiEnv:self.apiEnv];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -

- (void)observeValueForKeyPath:(nullable NSString *)keyPath ofObject:(nullable id)object change:(nullable NSDictionary<NSKeyValueChangeKey, id> *)change context:(nullable void *)context
{
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(apiEnv))])
    {
//        id domain = [self valueForKey:NSStringFromSelector(@selector(apiEnv))];
//        [ChangeEnvironmentManager changeEnvironmentActionWithApiEnv:[domain integerValue]];
//        [self.navigationController popViewControllerAnimated:YES];
    }
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
